package org.benxiong.iplay.http.request;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.benxiong.iplay.util.LogX;
import org.benxiong.iplay.util.PreferencesUtil;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.AsyncTask;

import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.BinaryHttpResponseHandler;
import com.loopj.android.http.RequestParams;

/**
 * @author Administrator
 * 
 */
public class RequestFactory {
	public static final String		URL_SERVER			= "http://api.gayddit.com/gdt2-webapi";
	public static final String		URL_LOGIN			= URL_SERVER + "/pub/login";

	public static final String		URL_REGISTER		= URL_SERVER + "/pub/signup";

	public static final String		URL_HAS_AVATOR		= URL_SERVER + "/pub/has-profile-picture";

	public static final String		URL_UPDATE_PROFILE	= URL_SERVER + "/member/profile/update";

	public static final String		URL_GET_PROFILE		= URL_SERVER + "/member/profile";

	public static final String		URL_UPLOAD_PHOTO	= URL_SERVER + "/photo/do-upload";

	public static final String		URL_MEMBERS			= URL_SERVER + "/member/find";

	public static final String		URL_MEMBER_FAV		= URL_SERVER + "/member/favorite";

	public static final String		URL_MEMBER_MEET		= URL_SERVER + "/member/meetup";

	public static final String		URL_MEMBER_BLOCK	= URL_SERVER + "/member/block";

	public static final String		URL_MEMBER_UNLOCK	= URL_SERVER + "/member/unlock";

	public static final String		URL_MY_PHOTOS		= URL_SERVER + "/member/my-photos";

	public static final String		URL_MOVE_PHOTOS		= URL_SERVER + "/photo/move-photos";

	public static final String		URL_DELETE_PHOTOS	= URL_SERVER + "/photo/delete-photos";

	public static final String		URL_SET_AS_PROFILE	= URL_SERVER + "/photo/set-profile-picture";

	public static String[]			allowedImgTypes		= new String[] { "image/png", "image/jpeg" };

	private AsyncHttpClient			client;
	private static RequestFactory	instance			= null;

	private RequestFactory() {
	}

	public static RequestFactory getInstance() {
		if (instance == null) {
			synchronized (RequestFactory.class) {
				if (instance == null) {
					instance = new RequestFactory();
				}
			}
		}

		return instance;
	}

	public void post(String url, RequestParams rParam,
			AsyncHttpResponseHandler respHandler) {
		client = new AsyncHttpClient();
		SharedPreferences sp = PreferencesUtil.getLoginInfo();
		client.addHeader("u", sp.getString(PreferencesUtil.USERNAME, null));
		client.addHeader("p", sp.getString(PreferencesUtil.PASSWORD, null));

		client.post(url, rParam, respHandler);
	}

	public void getPic(String url, BinaryHttpResponseHandler respHandler) {
		client = new AsyncHttpClient();
		SharedPreferences sp = PreferencesUtil.getLoginInfo();
		client.addHeader("u", sp.getString(PreferencesUtil.USERNAME, null));
		client.addHeader("p", sp.getString(PreferencesUtil.PASSWORD, null));

		client.get(url, respHandler);
	}

	public void cancel(Context context) {
		if (client != null)
			client.cancelRequests(context, true);
	}

	/**
	 * get image, file entity data from server, response content is handled
	 * through fRespHandler
	 * 
	 * @param url
	 * @param respHandler
	 */
	public void get(final String urlStr, final FileRespHandler fRespHandler) {
		new AsyncTask<Object, Object, byte[]>() {
			@Override
			protected byte[] doInBackground(Object... params) {
				HttpClient client = new DefaultHttpClient();

				HttpGet get = new HttpGet(urlStr);
				HttpResponse response;
				try {
					response = client.execute(get);
					int respCode = response.getStatusLine().getStatusCode();
					if (respCode == 200) {
						HttpEntity entity = response.getEntity();
						long length = entity.getContentLength();
						InputStream is = entity.getContent();
						if (is != null) {
							byte[] buf = new byte[1024];
							int ch = -1;
							ByteArrayOutputStream baos = new ByteArrayOutputStream();
							while ((ch = is.read(buf)) > 0) {
								baos.write(buf, 0, ch);
							}
							is.close();
							baos.flush();
							return baos.toByteArray();
						}
					} else {
						LogX.print("Error response code = " + respCode);
						return null;
					}

				} catch (ClientProtocolException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
					return null;
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
					return null;
				}
				return null;
			}

			@Override
			protected void onPostExecute(byte[] result) {
				super.onPostExecute(result);
				if (result == null) {
					fRespHandler.onFailure();
				} else {
					fRespHandler.onSuccess(result);
				}
			}

		}.execute();
	}
}
